package destinychild;

import aoshiScript.entity.WuNa;
import com.alibaba.fastjson.JSONObject;
import commons.entity.Constant;
import commons.entity.NativeCp;
import commons.util.GameUtil;
import fgoScript.entity.PointColor;
import fgoScript.exception.AppNeedRestartException;
import fgoScript.exception.AppNeedStopException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.awt.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @description: 百鬼夜行实体
 * @author: RENZHEHAO
 * @create: 2019-06-15 08:58
 **/
public class Light implements IModule {
    private boolean flag = true;
    private boolean tFlag = true;
    private WuNa wuna;
    private boolean goCheck = false;
    private boolean exFlag = true;
    private boolean exploreFlag = false;
    private long lastClickTimeStamp;
    private ThreadPoolTaskExecutor circleTPExcutor;
    private Object lock = new Object();
    public void settFlag(boolean tFlag) {
        this.tFlag = tFlag;
    }

    public void setWuna(WuNa wuna) {
        this.wuna = wuna;
    }

    public void setGoCheck(boolean goCheck) {
        this.goCheck = goCheck;
    }

    private LightData lightData;
    @Override
    public void start() {
        lastClickTimeStamp = System.currentTimeMillis();
        setFlag(true);
        settFlag(false);
        reFreshLightData();
        //单启动一个线程:实时点色教程操作。用来处理断线，重启，升级，补票等操作(脚本文件)
//        circleTPExcutor.execute(()-> {
//            LOGGER.info("《《《异常处理点击线程启动》》》");
//            try {
//                wuna.alwaysClickForStrategy("optionClick", 5000, true, false, false,false,0,Constant.DC + "/", null);
//            } catch (AppNeedRestartException e) {
//                LOGGER.error(e.getMessage(),e);
//            }
//            LOGGER.info("《《《异常处理点击线程结束》》》");
//        });
        // 线程1： 检测确认按钮
        circleTPExcutor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    checkConfirmButton();
                } catch (AppNeedStopException e) {
                    e.printStackTrace();
                }
            }
        });
        // 线程2： 设置点击参数
        doSetGreen();
        // 线程3： 夜行探索点击方法
        circleTPExcutor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    explore();
                } catch (AppNeedStopException e) {
                    e.printStackTrace();
                }
            }
        });
        LOGGER.info("是否运行状态： " + isFlag());
        GameUtil.delay(10000);
        while (circleTPExcutor.getActiveCount() != 0){
            delay(1000);
        }
        LOGGER.info("结束百鬼夜行！");
    }
    /**
     * @Description: 夜行探索点击方法
     * @return: void
     * @Author: RENZHEHAO
     * @Date: 2019/6/16
     */
    private void explore() throws AppNeedStopException {
        reFreshLightData();
        int count = 0;
        int exploreCount = 0;
        Color temp;
        // 检测button按钮和免费灯点
        while(isFlag() && isExFlag()){
            temp = GameUtil.getScreenPixel(lightData.getButtonPoint());
            if (GameUtil.likeEqualColor(temp, lightData.getButtonColor(), 1)){

                GameUtil.getMymouse().mouseMoveByPoint(lightData.getClickPoint(),true,true);

                exploreCount++;
                break;
            }
            temp = GameUtil.getScreenPixel(lightData.getFreeFinishPoint());
            if (GameUtil.likeEqualColor(temp, lightData.getFreeFinishColor(), 15)){
                LOGGER.info("无免费灯，结束夜行");

                GameUtil.getMymouse().mouseMoveByPoint(lightData.getClickPoint(),true,true);

                setFlag(false);
                synchronized (lock) {
                    lock.notifyAll();
                }
            }
            delay(1000);

        }

        while(isFlag() && isExFlag()){
            synchronized (lock) {
                lock.notifyAll();
            }
            GameUtil.getMymouse().mousePressAndRelease(lightData.getLmStep());
            delay(lightData.getClickDelay());
            setGoCheck(false);
        }

        delay(1000);
    }
    private void doSetGreen(){
        goCheck = false;
        circleTPExcutor.execute(new Runnable() {
            @Override
            public void run() {
                lightData.setLmStep(lightData.getSmStep());
                while(isFlag() && isExFlag()){
                    if(goCheck){
                    }
                    else{
                        synchronized (lock) {
                            LOGGER.info("程序暂停运行!");
                            try {
                                lock.wait();
                            } catch (InterruptedException e) {
                                LOGGER.error(e.getMessage(),e);
                            }
                            GameUtil.setWAIT_FLAG(false);
                            LOGGER.info("程序继续运行!");
                        }
                        setGoCheck(true);
                    }
                    checkGreen();
                    GameUtil.delay(20);
                }
                LOGGER.info("检测绿点结束!" + isFlag() + "_"+ isExFlag());
            }
        });
    }
    /**
     * @Description: 检测确认按钮
     * @return: void
     * @Author: RENZHEHAO
     * @Date: 2019/6/16
     */
    private void checkConfirmButton() throws AppNeedStopException {
        // 检测确认按钮
        Color checkColor;
        List<PointColor> pcList;
        int size;
        Point tempPoint;
        Color tempColor;
        do{
            checkColor = GameUtil.getScreenPixel(lightData.getConfirmPoint());
            if (GameUtil.likeEqualColor(checkColor, lightData.getConfirmColor(), 1)){
                this.setExFlag(false);
                synchronized (lock) {
                    lock.notifyAll();
                }
                // 等待线程<=1
                while(circleTPExcutor.getActiveCount() > 1){
                    LOGGER.info(circleTPExcutor.getActiveCount());
                    delay(1000);
                }
                this.setExFlag(true);

                GameUtil.getMymouse().mouseMoveByPoint(lightData.getConfirmPoint(),true,true);

                GameUtil.getMymouse().mousePressAndRelease(50);

                //继续执行探索
                circleTPExcutor.execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            explore();
                        } catch (AppNeedStopException e) {
                            e.printStackTrace();
                        }
                    }
                });
                // 继续 设置点击参数
                doSetGreen();
            }

            pcList = new ArrayList<>();
            pcList.add(new PointColor(lightData.getFinishPoint(),lightData.getFinishColor(), true));
            pcList.add(new PointColor(lightData.getStartPoint(),lightData.getStartColor(), true));
            pcList.add(new PointColor(lightData.getFreeReturnPoint(),lightData.getFreeReturnColor(), true));
            size = pcList.size();
            for (int i = 0; i < size; i++) {
                tempPoint = pcList.get(i).getPoint();
                tempColor = pcList.get(i).getColor();
                checkColor = GameUtil.getScreenPixel(tempPoint);
                if (GameUtil.likeEqualColor(checkColor, tempColor, 1)){

                    GameUtil.getMymouse().mouseMoveByPoint(tempPoint,true,true);

                    GameUtil.getMymouse().mousePressAndRelease(50);

                }
            }
            delay(1000);
            //超时处理 30分钟
            if((System.currentTimeMillis() - lastClickTimeStamp) > 30 * 60 * 1000){
                synchronized (lock) {
                    lock.notifyAll();
                }
                setFlag(false);
                while (circleTPExcutor.getActiveCount()>1){
                    delay(1000);
                }
            }
        }while (isFlag());
    }
    @Override
    public void stop() {
        synchronized (lock) {
            lock.notifyAll();
        }
        setFlag(false);
        while (circleTPExcutor.getActiveCount()!=0){
            delay(1000);
        }
        settFlag(true);
    }

    @Override
    public void toggle() {
        if (tFlag) {
            if ( circleTPExcutor.getActiveCount() == 0) {
                start();
            }
        } else {
            stop();
        }
    }

    private void checkGreen(){
        Color leftColor = GameUtil.getScreenPixel(lightData.getLeftPoint());
        Color rightColor = GameUtil.getScreenPixel(lightData.getRightPoint());
        int leftColorValue = leftColor.getGreen();
        int rightColorValueGreen = rightColor.getGreen();
        int rightColorValueRed = rightColor.getRed();
        int time = 0;
        if (rightColorValueGreen > 100 ){
            time = lightData.getLmStep()-lightData.getAmStep();
            time = time > lightData.getPmStep() ? time : lightData.getPmStep();
            lightData.setLmStep(time);
            LOGGER.info("Green " + lightData.getLmStep());
        }else if(rightColorValueRed > 100){
            time = lightData.getLmStep()-lightData.getAmStep();
            time = time > 10 ? time : 10;
            lightData.setLmStep(time);
            LOGGER.info("Red " + lightData.getLmStep());
        }else{
//            time = lightData.getLmStep()+lightData.getAmStep();
            lightData.setLmStep(lightData.getSmStep());
            LOGGER.info("growing "  + lightData.getLmStep());
        }

    }
    private void delay(int mscond){
        try {
            Thread.sleep(mscond);
        } catch (InterruptedException e) {
            LOGGER.error(e.getMessage(),e);
        }
    }

    public boolean isFlag() {
        return flag;
    }

    public void setFlag(boolean flag) {
        this.flag = flag;
    }

    public LightData getLightData() {
        return lightData;
    }
    public void reFreshLightData() {
        String filepath = NativeCp.getUserDir() + "/config/"+ Constant.DC +"/LightData.json";
        lightData = JSONObject.parseObject(GameUtil.getJsonString(filepath), LightData.class);
    }
    private static final Logger LOGGER = LogManager.getLogger(Light.class);

    public static void main(String[] args) {
    }

    public void setCircleTPExcutor(ThreadPoolTaskExecutor circleTPExcutor) {
        this.circleTPExcutor = circleTPExcutor;
    }

    public boolean isExFlag() {
        return exFlag;
    }

    public void setExFlag(boolean exFlag) {
        this.exFlag = exFlag;
    }

    public boolean isExploreFlag() {
        return exploreFlag;
    }

    public void setExploreFlag(boolean exploreFlag) {
        this.exploreFlag = exploreFlag;
    }
}
